<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
            v-model="queryParams.teamOneName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="排序" prop="orderByType">
        <el-select v-model="queryParams.orderByType" placeholder="请选择" clearable style="width: 200px"
                   @change="handleQuery">
          <el-option
              v-for="dict in group_find_order"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="queryParams.orderByTypeDesc" label="倒序" :true-value=2 :false-value=1
                     @change="handleQuery"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <!--        <el-button icon="Refresh" @click="resetQuery">清空</el-button>-->
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:guRef:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="id" align="center" prop="id"/>-->
      <!--      <el-table-column label="群id" align="center" prop="groupId"/>-->
      <!--      <el-table-column label="用户id" align="center" prop="userId"/>-->
      <el-table-column v-if="!groupId" label="群名称" align="center" prop="groupName"/>
      <el-table-column label="用户名称" align="center" prop="teamOneName"/>
      <el-table-column label="性别" align="center">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="总奖励" align="center" prop="awardCoin"/>
      <el-table-column label="胜率" align="center">
        <template #default="scop">
          {{ Number(scop.row.winRate).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="打水次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:boutStat:listPage']"
                     @click="skipPage(scope.row,'/group/boutStat')">
            {{ scope.row.competitionNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:participator:listPage']"
                     @click="skipPage(scope.row,'/group/participator')">
            {{ scope.row.activityNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="总局数" align="center" prop="totalBout"/>
      <el-table-column label="总胜局数" align="center" prop="winBout"/>
      <el-table-column label="总负局数" align="center" prop="loseBout"/>
      <el-table-column label="总得分" align="center" prop="totalScore"/>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="Ref">
import {AES_Decrypt, AES_Encrypt, decrypt} from "@/utils/jsencrypt.js";
import * as groupServer from "@/api/group/group.js";
import * as refServer from "@/api/group/ref.js";
import {rankWebList} from "@/api/group/boutStat.js";

const {proxy} = getCurrentInstance();
const {
  sys_user_sex,group_find_order
} = proxy.useDict("sys_user_sex","group_find_order");
const refList = ref([]);
const open = ref(false);
const allocateRoleF = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const resetFlag = ref(false);
const route = useRoute();
const router = useRouter();
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const userGroups = ref([])
const groupPermitMap = reactive(new Map())
const data = reactive({
  form: {},
  queryParams: {
    orderByType: 1,
    orderByTypeDesc: 2,
    pageNum: 1,
    startTime: null,
    findTime: null,
    endTime: null,
    pageSize: 10,
    groupId: groupId.value,
    userId: null,
    userName: null,
    adminType: null,
    sex: null,
    competitionNum: null,
    activityNum: null,
    activityCost: null,
    totalBout: null,
    winBout: null,
    loseBout: null,
    totalScore: null,
    awardCoin: null,
    loginDefault: null,
    tenantId: null,
  }
});

const {queryParams, form, rules} = toRefs(data);

function skipPage(row, path) {
  router.push({path: path, query: {userGroupRefId: AES_Encrypt(row.userGroupId), groupId: AES_Encrypt(row.groupId)}});
}

const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      userGroups.value.forEach(item => {
        groupPermitMap.set(item.id, item.adminType)
      })
      if (!groupId.value && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

function permitUpdate(groupId) {
  return groupPermitMap.get(groupId)
}

/** 查询用户和群关系列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    rankWebList(queryParams.value).then(response => {
      refList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  allocateRoleF.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupId: groupId.value ? groupId.value : null,
    userId: null,
    teamOneName: null,
    adminType: null,
    sex: null,
    competitionNum: null,
    activityNum: null,
    activityCost: null,
    totalBout: null,
    winBout: null,
    loseBout: null,
    totalScore: null,
    awardCoin: null,
    loginDefault: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/ref/export', {
    ...queryParams.value
  }, `ref_${new Date().getTime()}.xlsx`)
}

getList();
</script>
